<!DOCTYPE html>
          <head>
        <meta charset="utf-8">
            
            <title>
                「Python」Python中的Thread Local | ttdevs
            </title>
            <meta content="width=device-width, initial-scale=1" name="viewport">
            <meta name="theme-color" content="#4184f3">
            
            
            <link href="/favicon.ico" rel="icon"/>
            

            <link rel="stylesheet" href="/css/highlight.light.css">
            <link rel="stylesheet" href="/css/prism-customize.css">
            <link rel="stylesheet" href="/css/nav-icon.css">
            <link rel="stylesheet" href="/css/waves.min.css">
            <link rel="stylesheet" href="/css/jquery.tocify.css">
            <link rel="stylesheet" href="/css/main.css">
            <link rel="stylesheet" href="/css/nav-indicator.css">
            
  

  
  <!-- 谷歌统计 -->
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-97465173-1', 'auto');
    ga('send', 'pageview');

  </script>
  
            </meta>
        </meta>
    </head>

    <body>
        <header>
            <!-- cover image or sth. -->
        </header>
        <div id="main" class="m-scene">
            
<div class="nav-wrapper">

    <div class="container">
        <nav>
            <div class="logo wave">
                <a href="/" id="logo">
                    ttdevs
                </a>
            </div>
            <div class="nav-toggle-icon" >
                <div class="material-hamburger">
                    <span>
                    </span>
                    <span>
                    </span>
                    <span>
                    </span>
                </div>
            </div>
            <div class="menu-wrapper">
                <div class="nav-indicator">
                </div>
                <ul class="menus">
                    
                     
                        <li>
                            <a class="wave " href="/">
                                首页
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/archives">
                                归档
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/about">
                                关于
                            </a>
                        </li>
                     
                    
                   
                </ul>
            </div>
        </nav>
    </div>
</div>
            <div class="container content">
                <div class="scene_element scene_element--fadein">
                    <div class="row">
    <div class="main">
        <article>
          
          <header class="post-header with-cover" style="background-image:url('/1970/01/01/[Python]Python中的Thread Local/cover.jpg')" >
          
          </header>
          <h1 class="post-title">「Python」Python中的Thread Local</h1>

          <section class="post-info">
            <span class="post-date">1970/01/01</span>
            
            <span class="post-category">
                <a class="article-category-link" href="/categories/技术/">技术</a>
            </span>
            
            
            <span class="post-tags">
              <ul class="post-tag-list"><li class="post-tag-list-item"><a class="post-tag-list-link" href="/tags/Python/">Python</a></li></ul>
            </span>
            
          </section>

          <section class="post-content">
            <p>在线程内部，我们可能会用到线程内部的全局变量，这个也是比较常用的，因为可以全局访问。但是，如果线程内部的方法比较多，这个时候就需要我们一层层的传递，一层还好，二层三层甚至更多的时候就比较郁闷了。如果不传递，那么我们可能很难拿到线程内部的全局变量，这个时候我们就希望有个应用内的全局变量，供我们随时调用，thread local就可以满足我们的需求。看一个demo：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> threading</div><div class="line"></div><div class="line">local = threading.local()</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">end_learning</span><span class="params">()</span>:</span></div><div class="line">    print(<span class="string">'%s is finish.(Current Thread: %s)'</span> % (local.name, threading.current_thread().name))</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">start_learning</span><span class="params">()</span>:</span></div><div class="line">    print(<span class="string">'%s is learning.(Current Thread: %s)'</span> % (local.name, threading.current_thread().name))</div><div class="line">    end_learning()</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">learn_python</span><span class="params">(name)</span>:</span></div><div class="line">    local.name = name</div><div class="line">    start_learning()</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    thread1 = threading.Thread(target=learn_python, args=(<span class="string">'ttdevs1'</span>,), name=<span class="string">'Thread-A'</span>)</div><div class="line">    thread1.start()</div><div class="line"></div><div class="line">    thread2 = threading.Thread(target=learn_python, args=(<span class="string">'ttdevs2'</span>,), name=<span class="string">'Thread-B'</span>)</div><div class="line">    thread2.start()</div></pre></td></tr></table></figure>
<p>执行结果如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">ttdevs1 is learning.(Current Thread: Thread-A)</div><div class="line">ttdevs1 is finish.(Current Thread: Thread-A)</div><div class="line">ttdevs2 is learning.(Current Thread: Thread-B)</div><div class="line">ttdevs2 is finish.(Current Thread: Thread-B)</div><div class="line"></div><div class="line">Process finished with exit code 0</div></pre></td></tr></table></figure></p>
<p>从上面的demo中，我们可以还可以看到：线程A和线程B之间的数据是没有相互干扰的。</p>
<p>看到这里你可能会感觉这个不是特别简单嘛。是的，这个就是很简单，通过查看源码我们可以发现，他的实现就是通过一个字典来存放我们不同线程的数据，我们也可以自己实现的。既然系统实现了，我们就可以直接拿来用了。</p>
<p>比如，在实际的应用中，我们可以为每个线程保存一个数据库连接，在线程的不同方法中使用就非常的方便了。</p>
<p><img src="https://raw.githubusercontent.com/ttdevs/ttdevs.github.io/common/images/logo.png" alt="Create by ttdevs"></p>

          </section>
        </article>
        

       
        <div class="pager">
          
            <a class="post-prev pager-item" href="/1970/01/01/[Java]Java中获取本地IP和Port/" >
              <strong class="article-nav-caption">上一篇</strong>
              <p class="post-nav-title">「Java」Java中获取本地IP和Port</p>
            </a>
          
          
            <a class="post-next pager-item" href="/1970/01/01/[Flask]0x02给我们的Flask应用配置Supervisor/">
              <strong class="article-nav-caption">下一篇</strong>
              <p class="post-nav-title">「Flask」0x02给我们的Flask应用配置Supervisor</p>
            </a>
          
        </div>
        

         <!-- comments -->
        <div class="comment-section">
  
    


</div>

    </div>
    
    <aside>
        <div id="toc">
        </div>
    </aside>
    
</div>

                </div>
            </div>
        </div>
        <footer class="footer">
    <p>由<a href="http://hexo.io/" target="_blank">Hexo</a>强力驱动，搭载<a href="https://github.com/wayou/hexo-theme-gstyle">gstyle</a>主题</p>
    <p>
        &copy; 2017 ttdevs
    </p>
</footer>
<script src="/lib/jquery.js"></script>
<script src="/lib/waves.js"></script>
<script src="/lib/jquery-ui.js"></script>
<script src="/lib/jquery.tocify.js"></script>
<script src="/js/main.js"></script>

    </body>
</html>
